/**
 * @(#)SysParamServiceImpl.java
 * 
 *
 * 修订记录:

 */
package com.devframe.sysconfig.service.impl;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.devframe.sys.Constants;
import com.devframe.sys.encrypt.KeyEncryptor;
import com.devframe.sysbase.model.TSysParameter;
import com.devframe.sysbase.service.BaseService;
import com.devframe.sysconfig.service.SysParamService;
import com.devframe.sysconfig.storage.operate.ReaderCacheData;
import com.devframe.sysconfig.storage.operate.WriterCacheData;


@Service(value="sysParamService")
public class SysParamServiceImpl extends BaseService implements SysParamService {
	/**
	 * 日志
	 */
	private static final Logger LOG = Logger.getLogger(SysParamServiceImpl.class);
	/**
	 * 属性文件中值中key的前缀 KEY_PREFFIX="${"
	 */
	private static final String KEY_PREFFIX="${";
	/**
	 * 属性文件中值中key的后缀 KEY_SUFFIX="}"
	 */
	private static final String KEY_SUFFIX="}";
	/**
	 * 计数
	 */
	private int recursiveCnt=0;
	/**
	 * 最大的嵌套层次数
	 */
	private static final int MAX_RECURSIVE_CNT=5;
	
    /**
     * 数据存储写入器
     */
    @Autowired
    private WriterCacheData writerCacheData;
    /**
     * 数据存储读取器
     */
    @Autowired
    private ReaderCacheData readerCacheData;
    
	/**
	 * 加载系统参数表数据
	 */
	private void _load_parameter_table(){
		LOG.info("\n开始加载系统参数表...");
		List params =super.getBaseDao().sqlQueryForList("SELECT PARAM_CODE,PARAM_VALUE,NEED_ENCRYPT FROM T_SYS_PARAMETER");
		java.util.Iterator iter = params.iterator();
		String pCode;
		String needEncrypt;
		String pValue;
		while (iter.hasNext()) {
			//判断是否存在
			Map p = (Map) iter.next();
			pCode = (String) p.get("PARAM_CODE");
			needEncrypt = (String) p.get("NEED_ENCRYPT");
            pValue = (String) p.get("PARAM_VALUE");
            if("1".equals(needEncrypt)){
                pValue = KeyEncryptor.decrypt(pValue);
            }
			this.writerCacheData.addSysParam(pCode,pValue);
			//LOG.info(p.get("PARAM_CODE")+"="+p.get("PARAM_VALUE"));
		}
		LOG.info("\n系统参数表加载完成.");
	}
	/**
	 * 给层次计算器加1
	 * 
	 * @author:詹保山
	 */
	private void _addRecursiveCnt(){
		this.recursiveCnt++;
	}
	/**
	 * 获取层次计数器
	 * @return
	 * @author:詹保山
	 */
	private int _getRecursiveCnt(){
		return this.recursiveCnt;
	}
	/**
	 * 将层次计数器清0
	 * 
	 * @author:詹保山
	 */
	private void _clearRecursiveCnt(){
		this.recursiveCnt=0;
	}

	/**
	 * 递归调用获取值,最大层次不超过5
	 * May 7, 2012<br/>
	 * @描述：
	 * <br/> 
	 * @param value
	 * @param props
	 * @return
	 */
	private  String getVal(String value,ResourceBundle resBund){
		if(this._getRecursiveCnt()>=MAX_RECURSIVE_CNT){
			logger.error("属性值嵌套层次超过最大的层次数【max="+MAX_RECURSIVE_CNT+"】,系统将自动退出");
			System.exit(-1);
		}
		if(StringUtils.isEmpty(value)){
			return "";
		}
		if(value!=null && !(value.contains(KEY_PREFFIX)&& value.contains(KEY_SUFFIX))){
			return value;
		}
		//嵌套层次数加1
		this._addRecursiveCnt();
		if(StringUtils.isEmpty(value)){
			logger.warn("值出现为空，请重新确认");
			return "";
		}
		String val=value;
		int startIdx;
		int endIdx;
		String subKey;
		String subValue=null;
		while(val.indexOf(KEY_PREFFIX)!=-1 && val.indexOf(KEY_SUFFIX)!=-1){
			startIdx=val.indexOf(KEY_PREFFIX);
			endIdx=val.indexOf(KEY_SUFFIX);
			subKey=val.substring(startIdx+2, endIdx);
			if(readerCacheData.containsKeyInSysParam(subKey)){	
			   subValue=readerCacheData.getSysParam(subKey).toString();
			}
			if(subValue==null){
				subValue=resBund.getString(subKey);
			}
			val=val.substring(0, startIdx)+this.getVal(subValue, resBund)+val.substring(endIdx+1);
		}
		return val;
	}
	/**
	 * 加载系统参数属性文件数据
	 */	
	private void _load_parameter_porperties(){
		try{
			LOG.info("\n加载sysParameter.properties属性文件");
			ResourceBundle resBund=ResourceBundle.getBundle(Constants.SYS_PARAMETER_PORPERTIES);
			Enumeration<String> keys=resBund.getKeys();
			String key=null;
			String val=""; 
			while(keys.hasMoreElements()){
				key=keys.nextElement();
				//判断sysParams中是否存在该key的值
				val=this.getVal(resBund.getString(key),  resBund);
				if(readerCacheData.containsKeyInSysParam(key)){
					LOG.warn("系统参数表的配置的["+key+"="+readerCacheData.getSysParam(key)+"]和参数属性文件配置["+key+"="+val+"]出现重复，将参数文件配置的值进行替换掉");
				}
				//给层次计算器清零
				this._clearRecursiveCnt();
				this.writerCacheData.addSysParam(key, val);
			}
			LOG.info("\nsysParameter.properties属性文件加载完成");
		}catch(MissingResourceException e){
			LOG.error("未指定参数文件sysParameter.properties,不进行加载！");	
		}
	}
	
	/** 
	 * 系统参数初始化，也用于刷新系统参数
	 * @see com.fsti.dev.service.SysParamService#init()
	 */
	public void init(){
		//更新系统参数
		this.writerCacheData.cleanSysParamData();
		this._load_parameter_table();
		this._load_parameter_porperties();
	}
	
	
	
	/**
	 * 修改参数值
	 * @param key 参数名
	 * @param value 参数值
	 * @see com.fsti.dev.service.SysParamService#updateSysParam(java.lang.String, java.lang.String)
	 */
	public void updateSysParam(String key, String value) {
		if (this.readerCacheData.containsKeyInSysParam(key.trim().toUpperCase())) {
			TSysParameter param = (TSysParameter) super.getBaseDao().get(TSysParameter.class, key);
			if("1".equals(param.getNeedEncrypt())){
			    param.setParamValue(KeyEncryptor.encrypt(value));
			} else {
			    param.setParamValue(value);
			}
			super.getBaseDao().update(param);
		} else {
			throw new IllegalArgumentException("没有名为：" + key + "系统参数名，请检查T_SYS_PARAMETER表的设置。");
		}
	}
	public void setWriterCacheData(WriterCacheData writerCacheData) {
		this.writerCacheData = writerCacheData;
	}
	public void setReaderCacheData(ReaderCacheData readerCacheData) {
		this.readerCacheData = readerCacheData;
	}
	

	

}
